#include <cstring>
#include <queue>
#include <iostream>
using namespace std;

class Solution {
  public:
    /**
     * 代码中的类名、方法名、参数名已经指定，请勿修改，直接返回方法规定的值即可
     *
     *
     * @param grid int整型vector<vector<>>
     * @return int整型
     */
    int n, m;
    static const int N = 1e3 + 10;
    bool vis[N][N];
    using pii = std::pair<int, int>;
    queue<pii> qu; // 队列
    int count = 0;  // 好苹果的数量
    int minute = 0; // 消耗的时间
    // 方向矢量
    int dx[4] = {1, -1, 0, 0};
    int dy[4] = {0, 0, -1, 1};
    int rotApple(const vector<vector<int> >& g) {
        // write code here
        // memset(vis, false, sizeof(vis));
        n = g.size(), m = g[0].size();
        for (int i = 0; i < n; i++) {
            for (int  j = 0; j < m; j++) {
                if (g[i][j] == 2) {
                    qu.push({i, j});
                    vis[i][j] = true;
                }
                if (g[i][j] == 1) count++;
            }
        }

        bfs(g);
        if (count == 0)
            return minute;
        else
            return -1;
    }

    void bfs(const vector<vector<int>>& g) {
        queue<pii> tmp;
        while (qu.size()) {

            auto [x, y] = qu.front();
            qu.pop();
            for (int k = 0; k < 4; k++) {
                int i = x + dx[k], j = y + dy[k];
                if (i < 0 || i >= n || j < 0 || j >= m || vis[i][j]
                        || g[i][j] != 1)
                    continue;
                count--;
                vis[i][j] = true;
                tmp.push({i, j});
            }
            if (qu.empty() && tmp.size()){
                qu.swap(tmp);
                minute++;
            }
        }
    }
};

int main()
{

    Solution s;
    auto x = s.rotApple({{2, 1, 1},{1,0,1},{1,1,1}});
    cout << x << endl;
    return 0;
}